<template>
  <div class="dashboard-container">
    <div class="app-container">
      <empy-title :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="hBtnInExcel"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="hExportExcel"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="hAddEmpl"
          >新增员工</el-button>
        </template>
      </empy-title>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table
          border
          :data="list"
          row-key="id"
        >
          <el-table-column
            label="序号"
            sortable=""
            type="index"
          />
          <el-table-column label="头像">
            <template slot-scope="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                @click="hShowQrcode(row.staffPhoto)"
              >
              <!-- <span>{{ row }}</span> -->
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            sortable=""
            prop="username"
          />
          <el-table-column
            label="工号"
            sortable=""
            prop="workNumber"
          />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatterEmployment"
          />
          <el-table-column
            label="部门"
            sortable=""
            prop="departmentName"
          />
          <el-table-column
            label="入职时间"
            sortable=""
          >
            <template slot-scope="scope">{{ scope.row.timeOfEntry |formatDate }}</template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
          >
            <template slot-scope="{row}">
              <el-switch
                :value="row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            sortable=""
            fixed="right"
            width="280"
          >
            <template slot-scope="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/'+ row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
              >转正</el-button>
              <el-button
                type="text"
                size="small"
              >调岗</el-button>
              <el-button
                type="text"
                size="small"
              >离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="hEmplPermission(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDelEmployees(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="sizes,prev, pager, next,jumper"
            :page-sizes="[2,5,10,20]"
            :total="page.total"
            :page-size="page.size"
            @current-change="hchangePage"
            @size-change="hchangePageSize"
          />
        </el-row>
      </el-card>
      <!-- 自己封装的组件如果放在el-card中，它的父组件就是el-card，this.$parent就会报错  -->
      <add-empl :show-dialog.sync="isShowDialog" />
      <el-dialog
        title="二维码"
        :visible.sync="showCodeDialog"
        @close="imgUrl=''"
      >
        <el-row
          type="flex"
          justify="center"
        >
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色分配弹层 -->
      <empl-permission
        ref="emplPermission"
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import employeesData from '@/constant/employees'
import { formatDate } from '@/filters'
import AddEmpl from './add-Empl/addEmpl'
import QrCode from 'qrcode'
import EmplPermission from './components/emplPermission'

export default {
  components: {
    AddEmpl,
    EmplPermission
  },
  data () {
    return {
      list: [],
      page: {
        page: 1,
        size: 2,
        total: 0
      },
      isShowDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created () {
    this.loadEmployList()
  },
  methods: {
    async loadEmployList () {
      const { rows, total } = await getEmployeesList(this.page)
      // console.log(res)
      this.page.total = total
      this.list = rows
      console.log(this.list)
    },
    hchangePage (newPage) {
      this.page.page = newPage
      this.loadEmployList()
    },
    hchangePageSize (val) {
      this.page.size = val
      this.loadEmployList()
    },
    formatterEmployment (row, colum, cellValue) {
      // console.log(row, colum, cellValue)
      const obj = employeesData.hireType.find(item => item.id === cellValue)
      // console.log(obj)
      return obj ? obj.value : '未知' // 由于后台数据可能为空，所有进行判断，如果有值则正常转换，没有值则显示未知
    },
    // 导入表格跳转
    hBtnInExcel () {
      this.$router.push('/upload')
    },
    // 导出表格
    hExportExcel () {
      // 使用懒加载方式引入插件,属于promise异步引入，通过excel可以获取模块中所有导出的函数方法
      import('@/vendor/Export2Excel').then(async excel => {
        console.log(excel)
        // 1、定义字典
        // 2、将英文转成中文
        // 3、对时间和聘用形式进行转换
        // 4、将最后的结果以数组形式返回
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const header = Object.keys(headers)
        // 1、发送请求获取所有数据
        // 2、根据获取数据进行转换，转换成excel所需要的数据形式
        // 3、导出excel
        const { rows } = await getEmployeesList({ page: this.page.page, size: this.page.total })
        console.log(rows)
        const newUser = rows.map(user => {
          return this.enTocn(user, headers)
        })
        // console.log(newUser)
        // const header = ['姓名', '年龄']
        // const data = [
        //   ['张三', 18]
        // ]
        excel.export_json_to_excel({
          header,
          data: newUser
        })
      })
    },
    enTocn (user, headers) {
      const arr = []
      for (const key in headers) {
        // 通过英文key在user中取值，添加到一个新的数组中
        const enKey = headers[key]
        console.log(enKey)
        let value = user[enKey]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        } else if (enKey === 'formOfEmployment') {
          const obj = employeesData.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知'
        }
        arr.push(value || '未知')
      }
      console.log(arr)
      return arr
    },
    // 删除员工
    async hDelEmployees (id) {
      try {
        // 1、询问请求
        // 2、发送删除请求
        // 3、更新数据
        // 4、提示删除成功
        // ? 如果当前列表为0，判断页码是否需要减1
        await this.$confirm('请确认是否删除当前员工信息?')
        await delEmployee(id)
        this.loadEmployList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    hAddEmpl () {
      this.isShowDialog = true
    },
    hShowQrcode (imgUrl) {
      // 如果图片有值，则弹出二维码框，如果没有值则提示用户
      if (imgUrl) {
        this.showCodeDialog = true
        // 使用插件功能来生成二维码
        // 直接使用时dom还没有渲染会进行报错，vue异步更新，所以使用this.$nexttick 等待渲染后在调用
        // 1、渲染的Canvas标签
        // 2、渲染的信息
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, imgUrl, {
            width: 300

          })
        })
      } else {
        this.$message.warning('当前用户未上传头像图片')
      }

      // console.log(imgUrl)
    },
    hEmplPermission (id) {
      console.log(id)
      this.$refs.emplPermission.getRoleDetail(id)
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}
</style>
